import { Next } from "koa";
import result from '../utils/result';
import { token_key, jwt as jwtConf, OPEN_URL } from '../config/app';
import jwt from 'jsonwebtoken';

export function verifyToken() {
    return async (ctx: any, next: Next) => {
        const path = ctx.request.path;
        if (OPEN_URL.includes(path)) return await next();
        try {
            const token = ctx.request.header[token_key.USER_TOKEN];
            const user = jwt.verify(token, jwtConf.SECRET);
            ctx.user = user;
            await next();
        } catch (error) {
            new result(ctx).error(401);
        }
    };
}